package.path = package.path .. ";" .. PROJ_ROOT .. "/utils/?.lua;" .. PROJ_ROOT .. "/elasticsearch/?.lua;" .. PROJ_ROOT .. "/?.lua;" .. PROJ_ROOT .. "/gamelogic/?.lua;" .. PROJ_ROOT .. "/handler/?.lua;"

local skynet     = require "skynet"
local cjson      = require "cjson"
local datacenter = require "skynet.datacenter"
local redis      = require "skynet.db.redis"

require "functions"

require "skynet.manager"

local CMD = {}
local redisdb
local redisqueue
local runfork = true
local lasttime = nil


math.randomseed(tostring(os.time()):reverse():sub(1, 6))

--local queuename = gamename..'-'..'log'..'-'..'logqueue'

local function queuename()
    return string.format("%s-log-logqueue", APPNAME)
end

local function queuebakname()
    return string.format("%s-log-logqueuebackup", APPNAME)
end

local function queuefunc(cmd)
    skynet.error("queuefunc data=",cjson.encode(cmd.data))
    local ok,resp = pcall(skynet.call, "userd","lua", "addcoin", cmd.data)
    skynet.error("queuefunc resp="..cjson.encode(resp))
    return 'ok'
end


local function lpoprpush(queue, queuebak)
    local script = [[
        local v = redis.call('lpop', ARGV[1])
        if not v then
            return nil
        end
        redis.call('rpush', ARGV[2], v)
        return v
    ]]
    local t = redisdb:eval(script, 2, "log", "logqueuebackup", queuebak, queue)
    return t
end

local function copyback(queue, queuebak)
    local t = lpoprpush(queue, queuebak)
    while t do
        t = lpoprpush(queue, queuebak)
    end
end

skynet.start(function()
    skynet.dispatch("lua", function(session, source, cmd, ...)
        local f = assert(CMD[cmd])
        skynet.ret(skynet.pack(f(...)))
    end)

    local conf = {
        host = REDISQUEUE_CONF.ip,
        port = REDISQUEUE_CONF.port,
        db = 0
    }
    redisdb = redis.connect(conf)

    local k1 = queuename()
    skynet.error('queuename=', k1)
    local k2 = queuebakname()
    skynet.error('queuebakkname=', k2)
    copyback(k1, k2)
    skynet.fork(function()
        while runfork do
            if redisdb then
                local res = redisdb:brpoplpush(k1, k2, 10)
                skynet.error('brpoplpush res = ', res)
                if res then
                    local ok, ret = pcall(cjson.decode, res)
                    if ok and ret then
                        local ok = queuefunc(ret)
                        local a = redisdb:lrem(k2, -1, res)
                    end
                end
                if not lasttime or lasttime < os.time() - 10 then
                    lasttime = os.time()
                    redisdb:ping()
                end
            else
                skynet.sleep(1000)
            end
        end
    end)
    skynet.register "queued"
end)
